#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Written by Michele Comitini <mcm@glisco.it>
License: GPL v3

Adds support for Facebook  OAuth authentication to web2py.

This implementation works without any additional JavaScript such as
the \"Facebook JavaScript SDK\" (http://github.com/facebook/connect-js)

Requires Facebook Graph API python client library to be installed
under modules.  You can find the client library in Facebook Python
SDK: http://github.com/facebook/python-sdk.  The only required file is
facebook.py.

See http://developers.facebook.com/docs/api for more
info about the Graph API.
"""

import time
import cgi

from urllib import urlopen
from facebook import GraphAPI, GraphAPIError
AUTH_URL="https://graph.facebook.com/oauth/authorize"
TOKEN_URL="https://graph.facebook.com/oauth/access_token"

class FaceBookAccount(object):
    """
    Login will be done via  Facebook OAuth Framework, instead of web2py's
    login form.

    Include in your model (eg db.py)::
        # define the auth_table before call to auth.define_tables()
        auth_table = db.define_table(
           auth.settings.table_user_name,
           Field('first_name', length=128, default=""),
           Field('last_name', length=128, default=""),
           Field('username', length=128, default="", unique=True),
           Field('password', 'password', length=256,
           readable=False, label='Password'),
           Field('registration_key', length=128, default= "",
           writable=False, readable=False))

        auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)
        .
        .
        .
        auth.define_tables()
        .
        .
        .
    
        CLIENT_ID=\"<put your fb application id here>\"
        CLIENT_SECRET=\"<put your fb application secret here>\"
        from gluon.contrib.login_methods.facebook_account import FaceBookAccount
        auth.settings.login_form=FaceBookAccount(globals(),CLIENT_ID,CLIENT_SECRET)

    """
    def __redirect_uri(self):
        """Build the uri used by the authenticating server to redirect
        the client back to the page originating the auth request.
        """
        r = self.request
        http_host=self.request.env.http_x_forwarded_for
        if not http_host: http_host=self.request.env.http_host

        return 'http://%s%s'%( http_host, self.request.env.path_info )

    def accessToken(self):
        """Return the access token generated by the authenticating server.

        If token is already in the session that one will be used.
        Otherwise the token is fetched from the auth server.
        
        The token can be used by FaceBook GraphAPI.
        """
        if self.session.token:
            expires = self.session.token['expires']
            # reuse token until expiration
            if expires == 0 or expires > time.time():
                        return self.session.token['access_token']
        if self.code:
            tokendata = cgi.parse_qs(urlopen(TOKEN_URL + \
                               "?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s" % \
                               (self.client_id,
                                self.__redirect_uri(),
                                self.client_secret,
                                self.code)).read())
            self.session.token = dict([(k,v[-1]) for k,v in tokendata.items()])
            # set expiration absolute time
            self.session.token['expires'] == int(self.session.token['expires']) + time.time()
            return self.session.token['access_token']
        
        self.session.token = None
        return None

    def __init__(self, g, client_id, client_secret):
        self.globals = g
        self.client_id = client_id
        self.client_secret = client_secret
        self.graph = None
        self.code = None
        self.request = g['request']
        self.session = g['session']


    def login_url(self, next="/"):
        self._fb_login()
        return next

    def logout_url(self, next="/"):
        return ''

    def get_user(self):
        '''Returns the user using the Graph API.
        '''
        if not self.accessToken():
            return None
        
        if not self.graph:
            self.graph = GraphAPI((self.accessToken()))

        user = None
        try:
            user = self.graph.get_object("me")
        except GraphAPIError:
            self.session.token = None
            self.graph = None

        if user:
            return dict(first_name = user['first_name'],
                        last_name = user['last_name'],
                        username = user['id'])



    def _fb_login(self):
        '''This method redirects the user to the authenticating form
        on Facebook authentication server if the authentication code
        and the authentication token are not available to the
        application yet.

        Once the authentication code has been received this method is
        called to set the access token into the session by calling
        accessToken()
        '''
        if not self.accessToken():
            if not self.request.vars.code:
                self.globals['redirect'](AUTH_URL + "?client_id=%s&redirect_uri=%s" % (self.client_id, self.__redirect_uri()))
            else:
                self.code = self.request.vars.code
                self.accessToken()
                return self.code
        return None
